package com.example.iqiyitest.hztvpaysdk;

import android.app.Application;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;


public class HztvPayUtil {
    private static Application sApp;
    private static String sPubKey;
    private static String sPriKey;
    private static boolean sDebug = false;
    private static final String OFFICIAL_SIGNATURE_HASH = "z2TOYiCBjF6bnPqHGg6tckX8fwI=";
    private static final String PAY_APP_PACKAGE = "com.huazhu.hztvpay";

    /**
     *
     * @param app
     * @param pubKey
     * @param priKey
     * @throws SecurityException Throw SecurityException if the payment environment is not safe.
     */
    public static void init(Application app, String pubKey, String priKey) {
        sApp = app;
        sPubKey = pubKey;
        sPriKey = priKey;
    }

    public static void setDebug(boolean value) {
        sDebug = value;
    }

    public static boolean getDebug() {
        return sDebug;
    }

    public static String getPubKey() {
        return sPubKey;
    }

    public static String getPriKey() {
        return sPriKey;
    }

    /**
     *
     * @param context
     * @param payDetail
     * @throws IllegalStateException Throw an {@link IllegalStateException} if you haven't called init() or YeahInfoPay has not been installed.
     * @throws SecurityException If your device has unauthorized YeahPaySdk or YeahInfoPay.
     */
    public static void startToPay(Context context, PayDetail payDetail) {
        if (!checkSafety()) {
            throw new SecurityException("您所在的支付环境不安全, 支付终止!");
        }
        if (null == sApp || TextUtils.isEmpty(sPriKey) || TextUtils.isEmpty(sPubKey)) {
            throw new IllegalStateException("支付状态异常，请检查您是否已经调用init().");
        }

        Intent intent = new Intent();
        intent.setClassName(PAY_APP_PACKAGE, "com.huazhu.hztvpay.MainActivity");
        payDetail.order.packageName = context.getPackageName();
        try {
            payDetail.order.SeriseCode =  getLocalMacAddress();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        intent.putExtra("KEY_PAY_DETAIL", new Gson().toJson(payDetail));
        intent.putExtra("KEY_PUB_KEY", sPubKey);
        intent.putExtra("KEY_PRI_KEY", sPriKey);
        intent.putExtra("KEY_LANG", context.getResources().getConfiguration().locale);
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            throw new IllegalStateException("HztvPay还未安装!");
        }
    }

    private static boolean checkSafety() {
        if (sDebug) {
            return true;
        }
        if (!checkPkgSignatureHash(PAY_APP_PACKAGE).equals(OFFICIAL_SIGNATURE_HASH)) {
            return false;
        }
        return true;
    }

    private static String encrypt() {
        return null;
    }

    private static String bytesToMac(byte[] arr) {
        String result = "";
        if (arr != null) {
            for (int i = 0; i < arr.length; i++) {
                if (i > 0 && i < arr.length) {
                    result += ":";
                }
                result += String.format("%02x", arr[i]);
            }
        }
        return result;
    }



    public static String checkPkgSignatureHash(String pkg) {
        PackageInfo pkgInfo;
        try {
            pkgInfo = sApp.getPackageManager().getPackageInfo(pkg, PackageManager.GET_SIGNATURES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("hztvPay未安装");
        }
        String hash = "";
        for (Signature signature : pkgInfo.signatures) {
            try {
                hash += Base64.encodeToString(MessageDigest.getInstance("SHA").digest(signature.toByteArray()), Base64.NO_WRAP);
            } catch (NoSuchAlgorithmException e) { // Never happen
                e.printStackTrace();
            }
        }
        return hash;
    }

    private static String macAddress = null;
    public static String getLocalMacAddress() throws SocketException {
        if (macAddress == null) {
            try{
                macAddress = loadFileAsString("/sys/class/net/eth0/address").substring(0, 17);
                Log.d("macAddress",macAddress);
            } catch (IOException e) {
                Log.e("getLocalMacAddress",e.toString());
                return getMacAddress();
            }

        }
        return macAddress;
    }

    public static String loadFileAsString(String filePath) throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    /***
     * 获取以太网MAC
     *
     * @return String
     * @throws SocketException
     */
    public final static String getMacAddress() throws SocketException {
        if (macAddress == null) {

            macAddress = bytesToMac(NetworkInterface.getByInetAddress(
                    new InetSocketAddress(getLocalIpAddress(), 0).getAddress())
                    .getHardwareAddress());

        }
        return macAddress;

    }
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }
}
